package com.dede.monochromatism.activity

import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.view.Menu
import android.view.MenuItem
import android.widget.FrameLayout
import com.dede.applib.extends.makeSnackBar
import com.dede.applib.extends.showWarnImage
import com.dede.applib.extends.snackBar
import com.dede.applib.extends.warnShow
import com.dede.monochromatism.R
import com.dede.monochromatism.base.BaseActivity
import com.dede.monochromatism.fragment.SettingsFragment
import com.dede.monochromatism.util.ShellUtil
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.frameLayout
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.uiThread

/**
 * @author hsh
 * @date 2017/9/18 17:25.
 * @doc
 */
class SettingsActivity : BaseActivity() {

    private val container = 1001100

    lateinit var layout: FrameLayout

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        layout = frameLayout { id = container }

        val settingsFragment = SettingsFragment()
        fragmentManager.beginTransaction().replace(container, settingsFragment).commit()

        val hasPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_SECURE_SETTINGS)
        if (hasPermission != PackageManager.PERMISSION_GRANTED) {
            doAsync {
                val root = ShellUtil.requestRoot()
                if (root)
                    ShellUtil.requestPermission(packageName)
                if (!root) {
                    uiThread {
                        makeSnackBar(layout, "获取root权限失败！")
                                .showWarnImage()
                                .warnShow()
                    }
                }
            }
        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.menu_about -> {
                startActivity<AboutActivity>()
                return true
            }
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_setting, menu)
        return true
    }

    var lastTime: Long = 0
    override fun onBackPressed() {
        val first = System.currentTimeMillis()
        if ((lastTime + 2000) > first)
            super.onBackPressed()
        else {
            snackBar(layout, "再按一次退出")
            lastTime = first
        }
    }
}